import {createSlice} from '@reduxjs/toolkit';
import {fetchLocationsData} from '~/lib/directFetcher';

// 定义Location类型
export interface Location {
    id: string;
    name: string;

    [key: string]: any;
}

// 状态类型
interface LocationsState {
    items: Location[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
}

// 初始状态
const initialState: LocationsState = {
    items: [],
    status: 'idle',
    error: null,
};

// 创建slice
const locationsSlice = createSlice({
    name: 'locations',
    initialState,
    reducers: {
        // 手动更新locations列表的reducer
        setLocations(state, action) {
            state.items = action.payload;
        },
        // 开始获取数据
        fetchLocationsStart(state) {
            state.status = 'loading';
        },
        // 获取数据成功
        fetchLocationsSuccess(state, action) {
            state.status = 'succeeded';
            state.items = action.payload;
        },
        // 获取数据失败
        fetchLocationsFailed(state, action) {
            state.status = 'failed';
            state.error = action.payload || '获取位置失败';
        },
    },
});

// 导出actions
export const {
    setLocations,
    fetchLocationsStart,
    fetchLocationsSuccess,
    fetchLocationsFailed
} = locationsSlice.actions;

// 创建异步fetchLocations函数
export const fetchLocations = () => async (dispatch: any) => {
    try {
        dispatch(fetchLocationsStart());
        const response = await fetchLocationsData();
        dispatch(fetchLocationsSuccess(response || []));
    } catch (error) {
        dispatch(fetchLocationsFailed(error instanceof Error ? error.message : '未知错误'));
    }
};

// 导出reducer
export default locationsSlice.reducer; 